﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Areas.System.Controllers
{
    public class PageMenuController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="listPage"></param>
        /// <param name="pid"></param>
        /// <param name="layer"></param>
        /// <returns></returns>
        public ActionResult ShowMenuList(List<PageMenu> listPage, int pid = 0, int layer = 0)
        {
            ViewBag.Pid = pid;
            ViewBag.Layer = layer;
            return View(listPage);
        }

        public ActionResult ShowMenuSelectList(List<PageMenu> listPage, int pid = 0, int layer = 0)
        {
            ViewBag.Pid = pid;
            ViewBag.Layer = layer;
            return View(listPage);
        }
        /// <summary>
        /// 获取菜单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id = 0)
        {
            var result = ServiceFactory.PageMenuServiceInstance.Load(id);
            return View(result);
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(PageMenu model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            if (model.ID > 0)
            {
                if (ServiceFactory.PageMenuServiceInstance.IsExist(model.BelongApplicationType, model.PageName,
                    model.ParentID, model.ID))
                {
                    responseResult.Message = "菜单名称已经存在了";
                }
                else
                {
                    var pageMenu = ServiceFactory.PageMenuServiceInstance.LoadEntities(m => m.ID == model.ID).FirstOrDefault();
                    if (pageMenu != null)
                    {
                        pageMenu.IcoClass = model.IcoClass;
                        pageMenu.IsShow = model.IsShow;
                        pageMenu.PageName = model.PageName;
                        pageMenu.PageNameEN = model.PageNameEN;
                        pageMenu.PageNameRU = model.PageNameRU;
                        pageMenu.OrderIndex = model.OrderIndex;
                        pageMenu.PageUrl = model.PageUrl;
                        pageMenu.ParentID = model.ParentID;
                        pageMenu.BelongApplicationType = model.BelongApplicationType;

                        responseResult.Success = ServiceFactory.PageMenuServiceInstance.UpdateEntities(pageMenu);
                    }
                    else
                    {
                        responseResult.Message = "菜单不存在！";
                    }
                }
            }
            else
            {
                if (ServiceFactory.PageMenuServiceInstance.IsExist(model.BelongApplicationType, model.PageName,
                    model.ParentID))
                {
                    responseResult.Message = "菜单名称已经存在了";
                }
                else
                {
                    responseResult.Success = ServiceFactory.PageMenuServiceInstance.AddEntities(model).ID > 0;
                }
            }
            if (responseResult.Success)
                CacheHelper.Instance.RemoveAllCache();
            TempData["responseResult"] = responseResult;
            return RedirectToAction("Edit", new { id = model.ID });
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeletePageMenu(int id = 0)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Delete
            };
            var entity = ServiceFactory.PageMenuServiceInstance.Load(id);
            if (entity != null)
            {
                var list = ServiceFactory.PageToActionServiceInstance.LoadEntities(n=>n.PageID==id).ToList();
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        ServiceFactory.PageToActionServiceInstance.DeleteEntities(item);
                    }
                }
                responseResult.Success = ServiceFactory.PageMenuServiceInstance.DeleteEntities(entity);
                CacheHelper.Instance.RemoveAllCache();
            }
            else
            {
                responseResult.Message = "菜单不存在，删除失败";
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        /// <summary>
        /// 获取菜单按钮
        /// </summary>
        /// <param name="id">菜单Id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPageAction(int id = 0)
        {
            var result = ServiceFactory.PageToActionServiceInstance.LoadEntities(p => p.PageID == id).ToList();
            var actionIDList = "";
            if (result.Any())
            {
                actionIDList = string.Join(",", result.Select(o => o.ActionID).ToList());
            }
            return Json(new { success = true, PageActionIDList = actionIDList.Trim(',') });
        }

        /// <summary>
        /// 修改菜单按钮
        /// </summary>
        /// <param name="actionListId">按钮Id，多个用逗号隔开</param>
        /// <param name="id">菜单Id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateAction(string actionListId, int id = 0)
        {
            var addCount = 0;
            var removeCount = 0;
            var msg = "";
            var actionIDList = new List<string>(actionListId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ConvertAll(int.Parse);
            if (id > 0 && actionIDList.Count > 0)
            {
                foreach (var actionID in actionIDList)
                {
                    var pageToAction = new PageToAction
                    {
                        PageID = id,
                        ActionID = actionID
                    };
                    var entity = ServiceFactory.PageToActionServiceInstance.LoadEntities(
                       p => p.PageID == id && p.ActionID == pageToAction.ActionID).FirstOrDefault();
                    if (entity != null) continue;
                    if (ServiceFactory.PageToActionServiceInstance.AddEntities(pageToAction).ID > 0) ;
                    {
                        addCount++;
                    }
                }
            }
            var deletePageToActionList = ServiceFactory.PageToActionServiceInstance.LoadEntities(p => p.PageID == id && !actionIDList.Contains(p.ActionID)).ToList();
            foreach (var item in deletePageToActionList)
            {
                var roleToPageToAction = item.RoleToPageToAction.FirstOrDefault(p => p.PageToActionID == item.ID);
                if (roleToPageToAction != null)
                    msg += string.Format("，【按钮】[{0}] 已绑定到【角色】[{1}],无法移除", item.PageAction.ActionName,
                        roleToPageToAction.SystemRole.RoleName);
            }
            removeCount += deletePageToActionList.ToList().Sum(deleteRoleToPageToAction => ServiceFactory.PageToActionServiceInstance.DeleteEntities(deleteRoleToPageToAction) ? 1 : 0);
            CacheHelper.Instance.RemoveAllCache();
            return Json(new { success = true, message = string.Format("添加成功{0}个，移除{1}个{2}", addCount, removeCount, msg.Trim('，')) });
        }

    }
}
